

package com.gress.shop.util;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MD5Util {
    private static final Log logger = LogFactory.getLog(MD5Util.class);
    private static final int LO_BYTE = 15;
    private static final int MOVE_BIT = 4;
    private static final int HI_BYTE = 240;
    private static final String[] HEX_DIGITS = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    public MD5Util() {
    }

    private static String byteArrayToHexString(byte[] b) {
        StringBuffer buf = new StringBuffer();

        for(int i = 0; i < b.length; ++i) {
            buf.append(byteToHexString(b[i]));
        }

        return buf.toString();
    }

    private static String byteToHexString(byte b) {
        return HEX_DIGITS[(b & 240) >> 4] + HEX_DIGITS[b & 15];
    }

    public static String MD5(String origin) {
        if (origin == null) {
            throw new IllegalArgumentException("MULTI_000523");
        } else {
            String resultString = null;
            resultString = new String(origin);

            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            } catch (NoSuchAlgorithmException var3) {
                logger.error("Error in MD5Util.md5:" + var3);
            }

            return resultString;
        }
    }

    public static String hmac(String data, String secret) throws IOException {
        Object var2 = null;

        byte[] bytes;
        try {
            SecretKey secretKey = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacMD5");
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            bytes = mac.doFinal(data.getBytes("UTF-8"));
        } catch (GeneralSecurityException var5) {
            logger.error(var5);
            throw new IOException(var5);
        }

        return byte2hex(bytes);
    }

    private static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();

        for(int i = 0; i < bytes.length; ++i) {
            String hex = Integer.toHexString(bytes[i] & 255);
            if (hex.length() == 1) {
                sign.append("0");
            }

            sign.append(hex.toUpperCase());
        }

        return sign.toString();
    }

    public static void main(String[] args) {
        try {
            System.out.println(MD5("的是非得失法"));
            System.out.println(hmac("secret", "admin"));
        } catch (IOException var2) {
            var2.printStackTrace();
        }

    }
}
